authApp.value('page','school_dataFill');
authApp.controller("viewDController",function($scope,$http,$location,$getQueryString,$splice,Upload,$timeout, $cookies){
    var files = []
    $scope.preNum=$getQueryString("preNum");
    $scope.score = ''
    $scope.styles = {
        "display": 'none'
    }
    $scope.flag = false
    var requestJson={'fid':$getQueryString("pid"),'schoolId':$getQueryString("schoolId")};
    $scope.show = function(num) {
      var el = document.getElementById(num)
      if (el.style.display == 'none') {
          el.style.display = 'block'
      } else {
          el.style.display = 'none'
      }
    }
    $scope.slices = function(value) {
      var arr = value.split('/')
      return arr[arr.length - 1]
    }
    $scope.getAML=function(){
        $http({
            method:'post',
            url:apis.queryDetailed,
            data:requestJson,
        }).success(function(response){
            if(response.code=="000000"){
                $scope.list=response.data;
                //$scope.applyFile = response.data.applyFile
                if (!$scope.list.length) return
                angular.forEach($scope.list,function(data,index,array){
                    data.number = index + 1;
                    data.list && data.list.forEach(function(val) {
                      val.flielists = $scope.toarrys(val.files[0])
                    })
                });
            }else{
                alert(response.errorMsg);
            }
        }).error(function(){
            alert("服务器打瞌睡了，请稍等！");
        })
    }

    $scope.turnTo=function(pid){
        location.href="observationPoint.html?pid="+pid;
    }
    $scope.getAML();
    $scope.upload = function(file, errFiles, arraysublist) {
      arraysublist['fileLists'] = arraysublist['fileLists'] && arraysublist['fileLists'].length > 0 ? arraysublist['fileLists'] : []
      if (file) {
        if (/(\.jpg|\.png|\.gif)$/.test(file.type)) {
            $scope.uploadPics(file, errFiles, arraysublist)
        } else {
            $scope.uploadFiles(file, errFiles, arraysublist)
        }

      }
    }

    $scope.changed = function(score, arraylist) {
        arraylist.applyFile.s_score = score
    }

    $scope.deletecp = function(pid) {
      var obj1 = {'p_id': pid}
      $http({
        method:'post',
        url:apis.deleteApplyFile,
        data:obj1,
    }).success(function(response){
        if(response.code=="000000"){
            alert('自评表删除成功')
            $scope.getAML();
        }else{
            alert(response.errorMsg);
        }
    }).error(function(){
        alert("服务器打瞌睡了，请稍等！");
    })
    }

    $scope.selfpublish = function(url, arraylist) {
        var obj1 = {
          'son_target_id': arraylist.p_id,
          'schoolId': $cookies.get('account'),
          'fileUrl': url,
          's_score': arraylist.applyFile.s_score
        }
        $http({
            method:'post',
            url:apis.saveApplyFile,
            data:obj1,
        }).success(function(response){
            if(response.code=="000000"){
                $scope.score = ''
                $scope.getAML();
            }else{
                alert(response.errorMsg);
            }
        }).error(function(){
            alert("服务器打瞌睡了，请稍等！");
        })

    }
    $scope.publish =  function(file, errFiles, arraylist) {
        $scope.f = file;
        $scope.errFile = errFiles && errFiles[0];
        if (file) {
            
            file.upload = Upload.upload({
                url: apis.uploadfile,
                data: {file: file}
            });
            
            file.upload.then(function (response) {
                $timeout(function () {
                    if(response.data.code=="000000"){
                        console.log(response.data.data.url)
                      $scope.selfpublish(response.data.data.url, arraylist)
                    } else 
                        alert(response.data.errorMsg);
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        }
    }
     //上传pdf文件
     $scope.uploadFiles= function(file, errFiles, arraysublist) {
        $scope.f = file;
        $scope.errFile = errFiles && errFiles[0];
        if (file) {
            file.upload = Upload.upload({
                url: apis.uploadfile,
                data: {file: file}
            });

            file.upload.then(function (response) {
                $timeout(function () {
                    if(response.data.code=="000000"){
                        var obj = {}
                        obj.url = response.data.data.url
                        obj.fileName = response.data.data.fileName
                        arraysublist.fileLists.push(obj)

                        $scope.saveData(arraysublist.fileLists,arraysublist.p_id)
                    } else 
                        alert(response.data.errorMsg);
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        }
    }

    //上传图片
    $scope.uploadPics= function(file, errFiles, arraysublist) {
        $scope.f = file;
        $scope.errFile = errFiles && errFiles[0];
        if (file) {
            file.upload = Upload.upload({
                url: apis.pic,
                data: {file: file}
            });

            file.upload.then(function (response) {
                $timeout(function () {
                    if(response.data.code=="000000"){
                        var obj = {}
                        obj.url = response.data.data.url
                        obj.fileName = response.data.data.fileName
                        arraysublist.fileLists.push(obj)

                        $scope.saveData(arraysublist.fileLists,arraysublist.p_id)
                    }
                    else
                        alert(response.data.errorMsg);
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        }
    }


    $scope.saveData=function(list, pid){
        list = list.map(function(data) {
            return data.url
        })
        list = list.join(',')
        /*for(var key in checksleng){
            var keyIndex = key;
            for(var leng = 0;leng<checksleng[key]-1;leng++){
                keyIndex++;
                if($scope.conf[keyIndex]=="" || $scope.conf[keyIndex]==undefined || $scope.conf[keyIndex]==null){
                    $scope.conf[keyIndex] = "0";
                }
                if($scope.conf[key]=="" || $scope.conf[key]==undefined || $scope.conf[key]==null){
                    $scope.conf[key] = "0";
                }
                $scope.conf[key] += "/"+$scope.conf[keyIndex];
            }
            $scope.conf.splice(key+1,checksleng[key]-1);
        }*/


            var rJson={'itemId': pid,'value':list};
            $http({
                method:'post',
                url:apis.saveObservationPointOrSchoolItemData,
                data:rJson,
            }).success(function(response){
                if(response.code=="000000"){
                    $scope.getAML();
                }else{
                    alert(response.errorMsg);
                }
            }).error(function(){
                alert("服务器打瞌睡了，请稍等！");
            })
    }
    $scope.delete = function(id, num, arraysublist) {
        
        arraysublist = arraysublist.map(function(data, index){
            return data.s_url
        })
        $http({
            method:'get',
            url:apis.delete + '/' + id + '?value=' + encodeURIComponent(arraysublist[num]),
        }).success(function(response){
            if(response.code=="000000"){
                $scope.getAML();
            }else{
                alert(response.errorMsg);
            }
        }).error(function(){
            alert("服务器打瞌睡了，请稍等！");
        })
    }
    //校验电话号码
    $scope.deletfile = function(num, list, index, arraysublist) {
      if (!index) {
        $scope.delete(list, num, arraysublist)
        return
      }
      list.fileLists = list.fileLists.filter(function(data, index) {
            return index != num
        })
    }

    $scope.toarrys = function(list) {
        if (!list) return
        var arr = list.s_value.split(',')
        arr = [].slice.call(arr)
        return arr.map(function(data) {
           var obj = {}
           var name = data.split('/')
           obj['s_value'] = data
           obj['s_url'] = name[name.length - 1]
           return obj
        })
    }
    $scope.replaces=function(str) {
        return str.replace(/^\d+\.?/, '')
    }

    $scope.redirect = function(path) {
        // $http({
        // 	method:'get',
        // 	url:apis.downSchoolFile ,
        // 	params:{"path": path},
        // }).success(function(response){
        // 	if(response.code=="000000"){
        // 		//$scope.files
        // 		//$scope.files(response.data[0].p_id)\
        // 		totext(response.data)
        // 	}else{
        // 		alert(response.errorMsg);
        // 	}
        // }).error(function(){
        // 	alert("网络出现故障，请确认网络是否连接");
        // })
        if(typeof(path)=="undefined"||path==""||path==null){
            alert("请先上传文件");
            $scope.getAML();
        }else {
            if(path.indexOf(".doc")!=-1||path.indexOf(".docx")!=-1||path.indexOf(".pdf")!=-1){
                return window.location.href = apis.viewPdf + '?path=' + path
            }else if(path.indexOf(".jpg")!=-1||path.indexOf(".jpeg")!=-1||path.indexOf(".bmp")!=-1||path.indexOf(".gif")!=-1||path.indexOf(".tiff")!=-1||path.indexOf(".png")!=-1){
                return window.location.href = apis.viewPicture + '?path=' + path
            }else{
                return window.location.href = apis.downloadsExcel + '?path=' + path
            }

        }
    }
})